package com.example.demo.config;

import com.example.demo.annotate.NoPackageResult;
import com.example.demo.common.Result;
import com.example.demo.common.constant.ResultCode;
import com.example.demo.exception.BusinessException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

@RestControllerAdvice(basePackages = {"com.example.demo.controller"})
@Slf4j
public class ResponseResultConfig implements ResponseBodyAdvice<Object> {
    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
        // response是Result类型，或者注解了 NoPackageResult 都不进行包装
        return !methodParameter.getParameterType().isAssignableFrom(Result.class) && methodParameter.getMethodAnnotation(NoPackageResult.class) == null;
    }

    @Override
    public Object beforeBodyWrite(Object data, MethodParameter returnType, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest request, ServerHttpResponse response) {
        log.info("重新封装返回值格式");
        Result res = new Result();
        res.ok();

        // String类型不能直接包装
        if (data instanceof String) {
            ObjectMapper objectMapper = new ObjectMapper();
            try {
                // 将数据包装在Result里后转换为json串进行返回
                res.put("result", data);
                return objectMapper.writeValueAsString(res);
            }
            catch (JsonProcessingException e) {
                throw new BusinessException(ResultCode.PACKAGE_RESULT_ERROR);
            }
        }
        else {
            res.put("result", data);
        }

        return res;
    }
}
